#include <stdlib.h>
#include <string.h>
#include "cmsis_mem.h"
#include "cmsis_mem_tlsf.h"

#if defined(CPG_SUPPORT_FREERTOS_HEAP)
    void * pvPortMalloc( size_t xSize );
    void vPortFree( void * pv );
#elif defined(CPG_SUPPORT_TLSF_HEAP)
#else
    #error "a dynamic memory allocator should be specified!"
#endif

#if !defined(CPG_SUPPORT_FREERTOS_HEAP)
/**
 * @description:
 * @param {size_t} xWantedSize
 * @return {*}
 */
void *pvPortMalloc(size_t xWantedSize)
{
    return osMalloc(xWantedSize);
}

/**
 * @description:
 * @param {void} *pv
 * @return {*}
 */
void vPortFree(void *pv)
{
    osFree(pv);
}
#endif

/**
 * @description:
 * @param {size_t} xSize
 * @return {*}
 */
void * osMalloc(uint32_t xSize)
{
    void *mem = NULL;

#if defined(CPG_SUPPORT_FREERTOS_HEAP) && !defined(CFG_PLATFORM_SIMULATOR)
    mem = pvPortMalloc(xSize);
#elif defined(CPG_SUPPORT_FREERTOS_HEAP) && defined(CFG_PLATFORM_SIMULATOR)
    mem = malloc(xSize);
#elif defined(CPG_SUPPORT_TLSF_HEAP)
    mem = cmsis_mem_tlsf_malloc(xSize);
#else
    #error "osMalloc : a dynamic memory allocator should be specified!"
#endif
    if (mem)
    {
        memset(mem, 0, xSize);
    }
    return mem;
}

/**
 * @description:
 * @param {void *} pv
 * @return {*}
 */
void osFree( void * pv )
{
#if defined(CPG_SUPPORT_FREERTOS_HEAP) && !defined(CFG_PLATFORM_SIMULATOR)
    vPortFree(pv);
#elif defined(CPG_SUPPORT_FREERTOS_HEAP) && defined(CFG_PLATFORM_SIMULATOR)
    free(pv);
#elif defined(CPG_SUPPORT_TLSF_HEAP)
    cmsis_mem_tlsf_free(pv);
#else
    #error "osFree : a dynamic memory allocator should be specified!"
#endif
}

